package com.multition.demo03;

public class KeyInfo {
    private int keyMin;
    private int keyMax;
    private int nextKey;
    private String keyName;
    private int poolSize;

    public KeyInfo(String keyName, int poolSize){
        this.keyName = keyName;
        this.poolSize = poolSize;
        retrieveFromDB();
    }

    public synchronized int getNextKey() {
        if(nextKey > keyMax){
            retrieveFromDB();
        }
        return nextKey++;
    }

    // 从数据库获取刚刚设置的新一轮缓存值
    private void retrieveFromDB(){
        // 更新数据库中缓存的下一次取值key的键值
        String updateSQL = "UPDATE KeyTable SET keyValue = keyValue + " + poolSize + " WHERE keyName = '"+keyName+"'";
        String querySQL = "SELECT keyValue FROM KeyTable WHERE KeyName = '"+keyName+"'";
        // 执行 updateSQL
        // 执行 querySQL
        // 这里示意性的返回一个数字 100;
        int keyFromDB = 20;
        keyMax = keyFromDB;
        keyMin = keyMax - poolSize + 1;
        nextKey = keyMin ;
    }


}
